const HttpException = require("../exceptions/http_expetion");
const Article = require("../models/article");
const User = require("../models/user");
const Comment = require("../models/comment");



//添加评论
module.exports.addComment = async (req, res, next) => {
  try {
    //获取参数 slug 及 评论内容
    const { slug } = req.params
    const { body } = req.body.comment
    //获取文章及校验
    const article = await Article.findByPk(slug)
    if (!article) {
      throw new HttpException(404, '获取文章不存在！！！', 'article is not found!!!')
    }
    //获取评论用户及校验
    const user = await User.findByPk(req.user.email)
    if (!user) {
      throw new HttpException(404, '评论用户不存在！！！', 'user is not found!!!')
    }
    //创建评论
    let newComment = await Comment.create({ body })
    //创建关系
    await user.addComments(newComment)//用户和评论的关系
    await article.addComments(newComment)//文章和评论的关系
    //优化返回信息
    newComment.dataValues.user = {
      username: user.dataValues.username,
      bio: user.dataValues.bio,
      avatar: user.dataValues.avatar
    }
    //响应数据
    res.status(200)
      .json({
        status: 1,
        message: '添加评论成功',
        data: newComment
      })
  } catch (err) {
    next(err);
  }
};


//获取评论
module.exports.getComments = async (req, res, next) => {
  try {
    //获取参数 slug 
    const { slug } = req.params
    //获取文章及校验
    const article = await Article.findByPk(slug)
    if (!article) {
      throw new HttpException(404, '获取文章不存在！！！', 'article is not found!!!')
    }
    //获取文章评论列表
    const comment = await Comment.findAll({
      where: {
        articleSlug: slug
      },
      include: [{
        model: User,
        attributes: ['username', 'bio', 'avatar']
      }]
    })
    //响应数据
    res.status(200)
      .json({
        status: 1,
        message: '获取评论列表成功',
        data: comment
      })

  } catch (err) {
    next(err);
  }
};


//删除评论
module.exports.deleteComment = async (req, res, next) => {
  try {
    //获取参数 slug ; id
    const { slug, id } = req.params
    //获取文章及校验
    const article = await Article.findByPk(slug)
    if (!article) {
      throw new HttpException(404, '获取文章不存在！！！', 'article is not found!!!')
    }
    //获取评论及校验
    const comment = await Comment.findByPk(id)
    if (!comment) {
      throw new HttpException(404, '获取评论不存在！！！', 'comment is not found!!!')
    }
    //业务验证
    if (req.user.email !== comment.userEmail) {
      throw new HttpException(403, '当前用户没有删除评论权限!!!', 'The current user does not have permission to delete comments!!!')
    }
    //删除评论
    await Comment.destroy({ where: { id } })
    //响应数据
    res.status(200)
      .json({
        status: 1,
        message: '删除评论成功'
      })

  } catch (err) {
    next(err);
  }
};

